package com.kylin.core.order.web.facade.impl;

import com.kylin.core.commodity.query.handler.CommodityTranslator;
import com.kylin.core.common.web.facade.AbstractFacade;
import com.kylin.core.marketing.query.handler.MarketingTranslator;
import com.kylin.core.order.query.handler.OrderTranslator;
import com.kylin.core.user.query.handler.AddressTranslator;
import com.kylin.domain.commodity.provider.CommodityProvider;
import com.kylin.domain.commodity.vo.CommodityVO;
import com.kylin.domain.marketing.command.FindMarketingCommodityCommand;
import com.kylin.domain.marketing.provider.MarketingProvider;
import com.kylin.domain.marketing.vo.MarketingCommodityVO;
import com.kylin.domain.order.command.PlaceOrderCommand;
import com.kylin.domain.order.provider.OrderProvider;
import com.kylin.domain.user.command.FindDefaultAddressCommand;
import com.kylin.domain.user.provider.UserAddressProvider;
import com.kylin.domain.user.vo.UserAddressVO;
import com.kylin.domain.user.vo.WechatUserInfoVO;
import com.kylin.order.api.dto.req.CheckoutOrderReqDTO;
import com.kylin.order.api.dto.req.OrderListReqDTO;
import com.kylin.order.api.dto.req.PlaceOrderReqDTO;
import com.kylin.order.api.dto.resp.CheckoutOrderRespDTO;
import com.kylin.order.api.dto.resp.OrderDetailRespDTO;
import com.kylin.order.api.dto.resp.OrderListInfoRespDTO;
import com.kylin.order.api.dto.resp.PlaceOrderRespDTO;
import com.kylin.order.api.web.facade.OrderPlatformFacade;
import com.kylin.shared.common.Pagination;
import com.kylin.shared.common.ResponseWrapper;
import com.kylin.shared.common.anno.ArgsValid;
import com.kylin.shared.common.consts.Constants;
import com.kylin.shared.enums.ResultCodeEnum;
import com.kylin.shared.enums.RunningState;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RestController;

/**
 * 订单业务接口
 * @author Damon S.
 * @version v1.0.1
 * @date 2019年10月20日 16:07
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "订单开放接口")
public class OrderPlatformFacadeImpl extends AbstractFacade implements OrderPlatformFacade {

    private final CommodityProvider commodityProvider;
    private final CommodityTranslator commodityTranslator;
    private final OrderProvider orderProvider;
    private final OrderTranslator orderTranslator;
    private final MarketingProvider marketingProvider;
    private final MarketingTranslator marketingTranslator;
    private final UserAddressProvider addressProvider;
    private final AddressTranslator addressTranslator;


    @ArgsValid
    @Override
    @ApiOperation(value = "获取订单列表", notes = "分页获取订单列表")
    public ResponseWrapper<Pagination<OrderListInfoRespDTO>> list(OrderListReqDTO orderListReq) {
        orderProvider.queryOrders();
        return new ResponseWrapper<>();
    }


    @ArgsValid
    @Override
    @ApiOperation(value = "查询订单详情", notes = "查询指定订单详情")
    public ResponseWrapper<OrderDetailRespDTO> find(String orderNo) {
        orderProvider.findOrder();
        return new ResponseWrapper<>();
    }


    @ArgsValid
    @Override
    @ApiOperation(value = "检出下单信息", notes = "检出下单信息用于用户下单前的确认")
    public ResponseWrapper<CheckoutOrderRespDTO> checkout(CheckoutOrderReqDTO checkoutReq) {
        WechatUserInfoVO userInfo = getWxUserInfo();
        if (WechatUserInfoVO.EMPTY.equals(userInfo)) {
            return new ResponseWrapper<>(ResultCodeEnum.USER_NOT_EXIST);
        }
        CheckoutOrderRespDTO checkoutResp = new CheckoutOrderRespDTO();
        // 获取默认配送地址
        UserAddressVO address = addressProvider.findAddressDefault(
                new FindDefaultAddressCommand(Long.parseLong(userInfo.getUserId()))
        );
        // 存在默认地址则配置默认地址，不存在则放过
        if (!UserAddressVO.EMPTY.equals(address)) {
            checkoutResp.setAddress(addressTranslator.toUserAddressRespDTO(address));
        }
        // 获取商品信息(营销商品或普通商品)
        if (ObjectUtils.isEmpty(checkoutReq.getBoardId())) {
            CommodityVO commodity = commodityProvider.findCommodityByCommodityId(checkoutReq.getCommodityId());
            if (!CommodityVO.EMPTY.equals(commodity)) {
                checkoutResp.setItem(marketingTranslator.toMarketingBoardRespDTO(commodity));
            } else {
                log.error("指定商品不存在[UserId:{}, CommodityId:{}]", userInfo.getUserId(), checkoutReq.getCommodityId());
                return new ResponseWrapper<>(ResultCodeEnum.NOT_FOUND);
            }
        } else {
            MarketingCommodityVO mCommodityVO = marketingProvider.findMarketingCommodityLite(
                    FindMarketingCommodityCommand.builder()
                            .commodityId(checkoutReq.getCommodityId())
                            .boardId(checkoutReq.getBoardId()).build());
            if (!MarketingCommodityVO.EMPTY.equals(mCommodityVO) &&
                    RunningState.RUNNING.equals(mCommodityVO.getState())) {
                checkoutResp.setItem(marketingTranslator.toMarketingBoardRespDTO(mCommodityVO));
            } else {
                log.error("指定商品不存在[UserId:{}, CommodityId:{}]", userInfo.getUserId(), checkoutReq.getCommodityId());
                return new ResponseWrapper<>(ResultCodeEnum.NOT_FOUND);
            }
        }
        // 获取优惠券信息

        // 获取商家信息

        // 计算运费等信息
        return new ResponseWrapper<>(checkoutResp);
    }


    @ArgsValid
    @Override
    @ApiOperation(value = "用户下单", notes = "执行下单操作")
    public ResponseWrapper<PlaceOrderRespDTO> place(PlaceOrderReqDTO placeOrderReq) {
        WechatUserInfoVO userInfo = getWxUserInfo();
        if (WechatUserInfoVO.EMPTY.equals(userInfo)) {
            return new ResponseWrapper<>(ResultCodeEnum.USER_NOT_EXIST);
        }
        if (placeOrderReq.getQuantity() < Constants.INT_ONE ||
                placeOrderReq.getAddressId() < Constants.INT_ONE ||
                placeOrderReq.getCommodityId() < Constants.INT_ONE) {
            return new ResponseWrapper<>(ResultCodeEnum.BAD_REQUEST);
        }
        PlaceOrderCommand command = PlaceOrderCommand.builder()
                .userId(Long.parseLong(userInfo.getUserId()))
                .boardId(placeOrderReq.getBoardId())
                .commodityId(placeOrderReq.getCommodityId())
                .couponId(placeOrderReq.getCouponId())
                .addressId(placeOrderReq.getAddressId())
                .payMode(placeOrderReq.getPayMode())
                .payAmount(placeOrderReq.getPayAmount())
                .freight(placeOrderReq.getFreight())
                .quantity(placeOrderReq.getQuantity())
                .createdBy(Long.parseLong(userInfo.getUserId()))
                .message(placeOrderReq.getMessage()).build();

        return new ResponseWrapper<>(new PlaceOrderRespDTO(
                orderProvider.placeOrder(command),
                command.getPayAmount()
        ));
    }
}
